package com.base.myproject.client.HR.attendance;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BaseTreeStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.BO.TreeNodeModelData;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.tools.Tools;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.TreePanelEvent;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.DateTimePropertyEditor;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanelSelectionModel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckCascade;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckNodes;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * 考勤记录查询
 * @author Administrator
 *
 */
public class Att_records_check extends BaseJDBCPanel{
	String tree_depcode = null;// 讲当前树形结构中选中的部门id保存
	String tree_de_name = null;// 讲当前树形结构中选中的部门name保存

	TabPanel tabPanel = null;
	TreePanel<TreeNodeModelData> treePanel = null;
	// 创建树形结构的数据表
	BaseTreeStore<TreeNodeModelData> treeStore = null;
	
	BaseComboBoxForm<BusiObject> dep = new BaseComboBoxForm<BusiObject>("id","name","SystemInfo","",true);
	BaseComboBoxForm<BusiObject> att_type = new BaseComboBoxForm<BusiObject>("name","name","dictionary","where type='kc_type'",true);
	BaseComboBoxForm<BusiObject> type_remark = new BaseComboBoxForm<BusiObject>("remark","remark","hr_Attendance_type_setting","where 1=1",true);
	
	DateField seach_by_begin_date = new DateField();//查询开始日期
	DateField seach_by_end_date = new DateField();//查询结束日期
	TextField<String> by_name = new TextField<String>();//匹配姓名输入框
	Button seach_bt	= new Button("查询");//查询按钮
	Button seach = new Button("当天进场人员");//
	PagingToolBar toolBar = null;
	
	
	public Att_records_check() {
		init();
	} 
	public void init() {
		initWeigetx();
		registerMainStore(store);
	}   
	
	public void complete(){
		super.complete();
		getToolbarll().add(print);
		print.addListener(Events.OnClick, getListener());
	}
	
	BaseComboBoxForm<BusiObject> group1;
	public void initWeigetx() {
		
		toolBar = new PagingToolBar(30);
		HorizontalPanel cp=new HorizontalPanel();
	
		cp.add(new Label("时段从:"));
		seach_by_begin_date.setPropertyEditor(new DateTimePropertyEditor("yyyy-MM-dd"));
		seach_by_begin_date.setWidth(107);
		cp.add(seach_by_begin_date);
		cp.add(new Label(" 至:"));
		seach_by_end_date.setPropertyEditor(new DateTimePropertyEditor("yyyy-MM-dd"));
		seach_by_end_date.setWidth(107);
		cp.add(seach_by_end_date);
		cp.add(new Label(" 匹配姓名:"));
		by_name.setWidth(80);
		cp.add(by_name);
		cp.add(new Label(" 类型:"));
		att_type.setWidth(77);
		cp.add(att_type);
		cp.add(new Label(" 备注:"));
		type_remark.setWidth(77);
		cp.add(type_remark);
		
		
		/******/
		cp.add(new Label("进出类型:"));
		
		group1 = new BaseComboBoxForm<BusiObject>();
		ListStore attendancedStore = new ListStore();
        List list = new Vector();
        
        ModelData type1 = new BusiObject();
        type1.set("name", "进");
        type1.set("value", "I");
        list.add(type1);
        
        ModelData type2 = new BusiObject();
        type2.set("name", "出");
        type2.set("value", "O");
        list.add(type2);

        attendancedStore.add(list);
        group1.setTriggerAction(TriggerAction.ALL);
        group1.setWidth(60);
        group1.setStore(attendancedStore);
        group1.setDisplayField("name");
        group1.setValueField("value");
		/*******/
        cp.add(group1);
		seach_bt.addListener(Events.OnClick, getListener());
		cp.add(seach_bt);
		
		seach.addListener(Events.OnClick, getListener());
		cp.add(seach);
		

		VerticalPanel vp=new VerticalPanel();
		vp.setSpacing(5);
		vp.add(cp);
		
		ContentPanel panel2 = new ContentPanel();
		panel2.setHeaderVisible(false);
		panel2.add(getBaseGrid());
		panel2.setBottomComponent(toolBar);
		vp.add(panel2);
		
		ContentPanel center = new ContentPanel();
		center.setHeaderVisible(false);
		center.add(vp);
		/*********************/
		
		BorderLayout layout = new BorderLayout();
		this.setLayout(layout);
		BorderLayoutData northData = new BorderLayoutData(LayoutRegion.WEST,200);
		northData.setCollapsible(true);
		northData.setFloatable(true);
		northData.setHideCollapseTool(true);
		northData.setSplit(true);
		northData.setMargins(new Margins(5, 5, 0, 0));

		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
		centerData.setMargins(new Margins(5, 5, 0, 0));
		/***************************/
		ContentPanel panel = new ContentPanel();
		panel.setHeading("选择部门");
		panel.setCollapsible(true);
		panel.add(getTreePanel());
		
		add(panel, northData);
		add(center, centerData);	
	}
	/*************tree*********/
	TreePanel<TreeNodeModelData> getTreePanel() {
		if (treePanel == null) {
			initTreePanel();
		}
		return treePanel;
	}
	BaseTreeStore<TreeNodeModelData> getTreeStore() {
		if (treeStore == null) {
			initTreeStore();
		}
		return treeStore;
	}
	// 创建数据连接表
	BaseTreeStore<TreeNodeModelData> initTreeStore() {
		StoreInfo si = new StoreInfo();
		si
				.setSql("select icode,id,name from SystemInfo where id is not null order by id asc");
		si.setTreesortcolumn("id");
		si.setKeyname(new String[] { "icode" });
		si.setTablename("SystemInfo");
		treeStore = new BaseTreeStore<TreeNodeModelData>(si, false);
		treeStore.load();
		return treeStore;

	}
	// 实例化TreePanel
	TreePanelSelectionModel<TreeNodeModelData> tpsm = new TreePanelSelectionModel<TreeNodeModelData>();

	void initTreePanel() {
		// super.onRender();
		treePanel = new TreePanel<TreeNodeModelData>(getTreeStore());
		treePanel.setWidth(200);
		treePanel.setHeight(445);
		treePanel.setDisplayProperty("name");
		treePanel.setSelectionModel(tpsm);
		treePanel.setCheckStyle(CheckCascade.PARENTS);
		treePanel.setCheckNodes(CheckNodes.BOTH);
		treePanel.getStyle().setLeafIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.tree_file())); 
		treePanel.setCheckable(false);
		treePanel.setAutoLoad(true);

		treePanel.addListener(Events.OnClick,
				new Listener<TreePanelEvent<TreeNodeModelData>>() {
					public void handleEvent(TreePanelEvent<TreeNodeModelData> be) {
						String id = be.getItem().get("id").toString();
						//if (!id.equals("00")) {// 表示为主节点 不因有任何操作
							//set_grid(be);
						//}
						tree_depcode = id;// 讲当前树形结构中选中的部门id保存
						tree_de_name = be.getItem().get("name").toString();
					}
				});
	}
	/**********************************/
	
	// 创建数据表
	private BaseStore<BusiObject> store = null;
	
	public BaseStore<BusiObject> getStore(){
		if(store == null){
			createStore();
		}
		store.setToolBar(toolBar);
		store.initcompleted();
		return store;
	} 
	
	private BaseStore<BusiObject> createStore(){
		ModelType type = new ModelType();
		
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		
		type.addField("bcode");
		type.addField("bname");
		type.addField("systemid");
		type.addField("employinnertitle");
		type.addField("CHECKTIME");
		type.addField("outtype");
		type.addField("touse");
		type.addField("sensorid");
		type.addField("remark");
		
		StoreInfo info = new StoreInfo();
		info.setSql("select * from bcode where 1=2");
		store = new BaseStore<BusiObject>(type, info);
		return store;
	}
	
	// 创建一个grid
	BaseGrid<BusiObject> grid = null;
	BaseGrid<BusiObject> getBaseGrid() {
		if (grid == null) {
			createGrid();
		}
		return grid;
	}
	void createGrid() {
		CheckBoxSelectionModel<BusiObject> cbs = new CheckBoxSelectionModel<BusiObject>();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());
		ColumnConfig C1 = new ColumnConfig("bcode", "员工编号", 75);
		columns.add(C1);
		ColumnConfig C2 = new ColumnConfig("bname", "姓名", 65);
		columns.add(C2);
		ColumnConfig C3 = new ColumnConfig("systemid", "部门", 65);
		BaseComboBoxForm<BusiObject> dep = new BaseComboBoxForm<BusiObject>("id","name","SystemInfo","",true);
		dep.setReadOnly(true);
		C3.setRenderer(dep);
		columns.add(C3);
//		ColumnConfig C4 = new ColumnConfig("employinnertitle", "岗位", 85);
//		columns.add(C4);
		ColumnConfig C5 = new ColumnConfig("CHECKTIME", "打卡时间", 140);
		columns.add(C5);
		ColumnConfig C8 = new ColumnConfig("outtype", "进出类型", 100);
		columns.add(C8);
		ColumnConfig C6 = new ColumnConfig("touse", "类型", 85);
		columns.add(C6);
		ColumnConfig C7 = new ColumnConfig("sensorid", "打卡机器号", 85);
		columns.add(C7);
		ColumnConfig C9 = new ColumnConfig("remark", "备注", 105);
		columns.add(C9);
		
		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGrid<BusiObject>(getStore(), cm ,false,false);
		cbs.setSelectionMode(SelectionMode.SIMPLE);//控制是否可以多选每行后面的复选框
		grid.setSelectionModel(cbs);
		grid.setBorders(false);
		grid.setLoadMask(true);
		Tools.setResize(grid,0.80,0.85);
	}
	
	public void to_seach(String seach_type){
		String sql="";
		where = "";
		if(seach_type=="1"){	
			String dep_code=tree_depcode;//部门编码
			String begin_date=seach_by_begin_date.getRawValue();//开始时间
			String end_date=seach_by_end_date.getRawValue();//结束时间
			String name=by_name.getRawValue();
			String type=att_type.getRawValue();//类型
			String remark=type_remark.getRawValue();//类型
			String group=group1.getRawValue();
			if(!dep_code.equals("")){
				where+=" and a.systemid like '"+dep_code+"%25'";
			}
			if(!begin_date.equals("") && !end_date.equals("")){
				where+=" and c.CHECKTIME between '"+begin_date+"' and dateadd(day,1,'"+end_date+"') ";
			}
			if(!name.equals("")){
				where+=" and a.bname like '%25"+name+"%25' ";
			}
			if(!type.equals("")){
				where+=" and c.touse = '"+type+"' ";
			}
			if(!remark.equals("")){
				where+=" and c.remark= '"+remark+"' ";
			}
			if(!group.equals("")){
				where+=" and  c.checktype ='"+group+"'" ;
			}
			where.replaceAll("%25", "%");
       
			sql="select SSN as bcode,a.bname,b.employinnertitle,a.systemid,c.CHECKTIME,c.touse,c.sensorid, " +
				" c.checktype as outtype,c.remark " +
				" from bcode as a,bcode_job as b,attendance_view as c " +
				"where a.bcode=b.bcode and a.bcode=right(rtrim(c.SSN),4) "+where + " order by checktime desc";
		}else{
			sql="select  SSN as bcode,a.bname,b.employinnertitle,a.systemid,c.CHECKTIME,c.touse,c.sensorid, " +
				" c.checktype as outtype,c.remark " +
				" from bcode as a,bcode_job as b,attendance_view as c "+
				" where a.bcode=b.bcode and a.bcode=right(rtrim(c.SSN),4)   "+
				" and CONVERT(varchar(10),c.CHECKTIME,120)= CONVERT(varchar(10),getdate(),120) "+
				" and c.checktype ='进'  "+
				" and  c.CHECKTIME>isnull((select max(CHECKTIME) "+
				" from attendance_view "+
				" where right(ssn, 4)=a.bcode  and  "+
				" c.checktype !='进' "+
				" and CONVERT(varchar(10),CHECKTIME,120)= CONVERT(varchar(10),getdate(),120) "+
				" ),'') ";
			where = " and CONVERT(varchar(10),c.CHECKTIME,120)= CONVERT(varchar(10),getdate(),120) "+
					" and c.checktype ='进'  "+
					" and  c.CHECKTIME>isnull((select max(CHECKTIME) "+
					" from attendance_view "+
					" where right(ssn, 4)=a.bcode  and  "+
					" c.checktype !='进' "+
					" and CONVERT(varchar(10),CHECKTIME,120)= CONVERT(varchar(10),getdate(),120) "+
					" ),'') ";
		}	
		grid.getStore().getStoreinfo().setSql(sql);
		grid.getStore().reload();
		grid.getView().refresh(true);
	}
  
	String where = "";
	int sync = 0;
	Listener<BaseEvent> defaultlistener;

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}
		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.Select) {

						}  else if (be.getType() == Events.OnClick) {
							if (be.getSource().equals(seach_bt)) {
								//tree_depcode 	tree_de_name 
								if(tree_depcode==null ){
									MessageBox.alert("警告", "请选择查询部门",null);
								}else{
									if(seach_by_begin_date.getRawValue().equals("")|| seach_by_end_date.getRawValue().equals("")){
										MessageBox.alert("警告", "请选择查询时段",null);
									}else{
										to_seach("1");//1代表查询考勤记录
									}
								}
							}
							
							if (be.getSource().equals(print)) {
								if (where.equals("")) {
									MessageBox.alert("提示", "请查询数据后再打印，谢谢", null);
									return;
								}
								Window.open(GWT.getHostPageBaseURL() + "hr_Jsp/rptAttendanceRecord.jsp?where=" + where, "_blank","menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");
							}
							//当天进场人数
							if (be.getSource().equals(seach)) {
								to_seach("2");//2代表当天进场考勤记录
							}
							
						} else if (be.getType() == Events.Change) {
							
						}
					}
				} finally {
					sync--;
				}
			}

		};
		return defaultlistener;
	}	
	
}
